Vue.use(Vuex);

Vue.component(
    'MsC',
    {
        template:`<p>
        From MsC 
        count: {{count}} 
        rev: {{rev}} 
        count is {{than}}
        <button v-on:click="increment">add 1 in component</button>
        </p>`,

        data:function (){
            return {

            }
        },

        methods:
            Object.assign(
                Vuex.mapMutations(['increment']),
                Vuex.mapActions(['incrementAsyn'])
            ),

        computed:
            Object.assign(
                Vuex.mapState(['count','rev']),
                Vuex.mapGetters(['than'])
            )
    }
);

var store = new Vuex.Store({
    state: {
        count:0,
        rev:0
    },
    mutations:{
        increment(state){
            state.count++;
            state.rev--;
        },
        sub(state){
            state.count -= 1;
            state.rev++;
        },
        incrementX(state , p){
            state.count += p.step;
            state.rev -= p.step;
        }
    },
    getters:{
        "than" : function(state , getters){
            if(state.count > 0){return "greater than 0";}
            if(state.count < 0){return "less than 0";}
            if(state.count = 0){return "equals to 0";}
        }
    },
    actions:{
        "incrementAsyn":function({commit , state}){
            setTimeout(function(){
                commit("increment");
            } , 2000);
        }
    }
});

// store要响应式。
var app_data = {
    "message": 'Hello Vue!',
    store
};

var app = new Vue({
    el: '#app',
    data: app_data,

    // store还要为子组件全局。
    store,
    methods:{
        makeEmpty:function(){
            return {};
        },
        add1:function(){
            this.$store.commit('increment' , this.makeEmpty());
        },
        addX:function(x){
            this.$store.commit('incrementX' , {step:x});
        },
        add1Asyn:function(x){
            var p = this.$store.dispatch('incrementAsyn');
        },
        sub1:function(){
            this.$store.commit('sub');
        }
    }
});